package net.csdra.libraryborrowing.service.user;

import net.csdra.libraryborrowing.domain.user.User;
import net.csdra.libraryborrowing.domain.user.UserRepository;
import net.csdra.libraryborrowing.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.util.Assert;

import java.nio.file.AccessDeniedException;
import java.util.List;

/**
 * Created by add on 2017/10/17.
 */
public class UserManageServiceImpl implements UserManageService {

    UserRepository userRepository;
    CurrentUserInfo currentUserInfo;

    @Autowired
    public UserManageServiceImpl(UserRepository userRepository, CurrentUserInfo currentUserInfo) {
        this.userRepository = userRepository;
        this.currentUserInfo = currentUserInfo;
    }


    @Override
    public User createUser(CreateUser createUser) throws AccessDeniedException {
        Assert.notNull(createUser, "参数不能为空");
//        User current = this.currentUserInfo.get();
        User usr = Utils.createAutoSet(User.class, "cpjia");
        Utils.copy(createUser, usr);
        this.userRepository.save(usr);
        User result = new User();
        Utils.copy(usr, result);
        return result;
    }

    @Override
    public User updateUser(UpdateUser updateUser) throws AccessDeniedException {
        Assert.notNull(updateUser, "更新参数不能为空");
        User current = this.currentUserInfo.get();
        User usr = Utils.createAutoSet(User.class, current.getUserName());
        Utils.copy(updateUser, usr);
        this.userRepository.save(usr);
        User result = new User();
        Utils.copy(usr, result);
        return result;
    }

    @Override
    public User getUserById(GetUserById getUserById) {
        return this.userRepository.findOne(getUserById.getId());
    }

    @Override
    public List<User> getUserLikeUserName(GetUserLikeUserName getUserLikeUserName) {
        return this.userRepository.findByUserName(getUserLikeUserName.getKey(),
                new PageRequest(0, Integer.parseInt(getUserLikeUserName.getResultNum()), new Sort(Sort.Direction.DESC)));
    }

    @Override
    public Page<User> getUserPage(GetUserPage getUserPage) {
        return null;
    }

    @Override
    public Page<User> getUserByAuthoryPage(GetUserByAuthoryPage getUserByAuthoryPage) {
        return null;
    }
}
